package org.boot.ssm.wxshop.web.controller;

import org.boot.ssm.wxshop.util.UploadUtil;
import org.boot.ssm.wxshop.web.common.JsonResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: wxshop
 * @description: 所有文件上传统一控制器
 * @author: Parasomnia
 * @create: 2018-03-18 16:21
 **/
@Controller
@RequestMapping("/upload")
@ResponseBody
public class UploadController {

    /**
     * 普通的单图片上传接口
     * @param request 请求
     * @param file 上传文件
     * @return 上传信息
     */
    @RequestMapping("/simpleupload")

    public JsonResult fileUpload(HttpServletRequest request, MultipartFile file) {
        return new JsonResult(200, "上传成功", UploadUtil.fileUpload(request, file, "/upload"));
    }

    /**
     * 富文本编辑器上传组件
     * @param request 请求
     * @param files 上传多个文件
     * @return 上传信息
     */
    @RequestMapping("/editorupload")
    public Map<String,Object> editorUpload(HttpServletRequest request, List<MultipartFile> files){
        Map<String,Object> json = new HashMap<>();
        List<String> data = new ArrayList<>();
        try {
            for(int a = 0;a<files.size();a++){
                String temp = UploadUtil.fileUpload(request,files.get(a),"upload");
                data.add(temp);
            }
            json.put("errno",0);
            json.put("data",data);
        } catch (Exception e) {
            json.put("errno",500);
            json.put("data",null);
        }
        return json;
    }


}
